package net.tribal.comic.controllers

import net.tribal.comic.entities.AlterPage
import net.tribal.comic.entities.Page
import net.tribal.comic.entities.User
import net.tribal.comic.entities.Comment


class AlterPageController {
	def pageService

	
	/**
     *  Les accions 'delete', 'save' i 'update' nom�s accepten peticions POST
     */
    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    
	/**
	 * Acci� per defecte
	 */
    def index = { redirect(action: "list", params: params) }
	
                         	
	/**
     * Commuta entre entre el modes de visionat "Coverflow" i "Llistat" 
     */
	def changeView = {
		session['alterPageViewMode'] = (session['alterPageViewMode'] == 'list') ? "flow" : "list"
		redirect(controller:"alterPage", action: "list", params: params)
		return
	}
	
	
	/**
	    * Mostra les p�gines alternatives d'una p�gina
	    * 
	    * La cerca podr� ser filtrada per t�tol segons el valor del camp 'searchAjax'
	    * 
	    * return GSP
	    *  render - /alterPage/listContent
	    *  render - /alterPage/list
	    */
    def list = {
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		
		def list = pageService.getActiveAlterPages(params.max, params.offset?.toInteger(), params.sort, params.order, session['user']?.admin, params?.searchAjax, params.fromId)
		
		if(params.searchAjaxAction != null){
	        //	La cerca es as�ncrona
			render(template:"/alterPage/listContent",model:[alterPageInstanceList:list['data'], alterPageInstanceTotal:list['count'], fromId:params.fromId])
			return
		} 
		
        // La cerca es s�ncrona
		render(view:"/alterPage/list", model:[alterPageInstanceList: list['data'], alterPageInstanceTotal: list['count'], fromId:params.fromId])
        return
    }

	/**
	 * Mostra la pantalla per crear una p�gina alternativa
	 * 
	 * return GSP
     *  render - /alterPage/create
	 */
    def create = {
        def alterPageInstance = new AlterPage()
        alterPageInstance.properties = params

		if(params.id) {	
			// si existeix, venim de veure una pagina, sino es una accio directe
			alterPageInstance.page = Page.get(params.id.toLong())
		}
		
        render(view:"/alterPage/create", model:[alterPageInstance: alterPageInstance, page:alterPageInstance.page, 'fromId':params.fromId])
        return 
    }
	
	
	/**
     * Desa un p�gina alternativa
     * 
     * return GSP
     *  redirect /alterPage/list
     *  render - /alterPage/create
     */	
	def save = {
        def alterPageInstance = new AlterPage(params)
        alterPageInstance.createdBy = session['user']
		pageService.add( alterPageInstance, request.getFile('file') )
		
        if (!alterPageInstance.hasErrors() ) {
            flash.message = "flash.alterPage.created"
            flash.args = [alterPageInstance.id]
            redirect(controller:"page", action:"show", id:params['page.id'])
            return
        }

        render(view:"/alterPage/create", model:[alterPageInstance: alterPageInstance])
        return
    }
	
	
	/**
     * Mostra una p�gina alternativa
     * 
     * retun
     *  redirect - /alterPage/list
     *  render - /alterPage/editFile
     */
	def show = {
        def alterPageInstance = AlterPage.get(params.id)
        if (!alterPageInstance) {
            flash.message = "alterPage.not.found"
            flash.args = [params.id]
            redirect(controller:"alterPage", action:"list")
            return
        }
		
		def userSession = User.get(session.user?.ident())
    	def yourOldRate = pageService.getRateFromAlterPageAndUser ( alterPageInstance, userSession )
    	
		render(view:"/alterPage/show", model:[alterPageInstance:alterPageInstance, yourRate:yourOldRate])
        return
    }
	
	
	/**
	 * M�tode que mostra les dades d'una p�gina alternativa
     * 
     * retun
     * 	redirect - /alterPage/list
     *  render - /alterPage/editProfile
	 */
	def editProfile = {
        def alterPageInstance = AlterPage.get(params.id)
        
        if (!alterPageInstance) {
            flash.message = "alterPage.not.found"
            flash.args = [params.id]
            redirect(controller:"alterPage", action:"list")
        }
        else {
			render (view:"/alterPage/editProfile", model:[alterPageInstance: alterPageInstance] )
        }
    }

	
	/**
     * M�tode que mostra la pantalla per canviar l'imatge de la p�gina alternativa
     * 
     * retun
     * 	redirect - /alterPage/list
     *  render - /alterPage/editProfile
     */
	def editFile = {
        def alterPageInstance = AlterPage.get(params.id)
        if (!alterPageInstance) {
            flash.message = "alterPage.not.found"
            flash.args = [params.id]
            redirect(controller:"alterPage", action: "list")
            return
        }

        render (view:"/alterPage/editFile", model:[alterPageInstance: alterPageInstance] )
        return
    }


	/**
	 * Actualitza les dades de la p�gina alterna
	 * 
	 * retun
     * 	redirect - /alterPage/list
     *  render - /alterPage/editProfile
     *  redirect - /alterPage/show
	 */
	def updateProfile = {
		def alterPageInstance = AlterPage.get (params.id)
		
		if ( !alterPageInstance ) {
			flash.message = "alterPage.not.found"
            flash.args = [params.id]
            redirect(controller:"alterPage", action:"list")
            return
		}

		alterPageInstance = pageService.changeProfile( alterPageInstance, request.getFile('file') )

		if ( userInstance.hasErrors() ) {
			render(view:"/alterPage/editProfile", model: [alterPageInstance: alterPageInstance])
			return
    	}
		
		flash.message = "alterPage.updated"
        flash.args = [params.id]
        redirect(controller:"alterPage", action:"show", id: alterPageInstance.id)
		return
	}

	
	/**
	 * Actualitza l'imatge de la p�gina alterna
	 * 
	 * retun
     * 	redirect - /alterPage/list
     *  render - /alterPage/editFile
     *  redirect - /alterPage/show
	 */
	def updateFile = {
		def alterPageInstance = AlterPage.get (params.id)
		if ( !alterPageInstance ) {
			flash.message = "alterPage.not.found"
            flash.args = [params.id]
            redirect(controller:"alterPage", action:"list")
            return
		}

		alterPageInstance = pageService.changeFile ( alterPageInstance, request.getFile('file') )

		if ( alterPageInstance.hasErrors() ) {
			render(view:"/alterPage/editFile", model: [alterPageInstance: alterPageInstance])
			return
    	}
		
		flash.message = "alterPage.updated"
        flash.args = [params.id]
        redirect(controller:"alterPage", action:"show", id: alterPageInstance.id)
    	return
	}

	
	/**
	 * Elimina una pagina alternativa
	 * 
	 * retun
     * 	redirect - /alterPage/list
     *  redirect - /alterPage/show
	 */
    def delete = {
		def alterPageInstance = pageService.deleteAlterPage( AlterPage.get(params.id) )
		
        if (!alterPageInstance) {
			flash.message = "alterPage.not.found"
			flash.args = [params.id]
			redirect(controller:"alterPage", action:"list", params:[fromId:params.fromId])
			return
		}
		
		if (!alterPageInstance.hasErrors()) {
            flash.message = "alterPage.deleted"
            flash.args = [params.id]
            redirect(controller:"alterPage", action:"list", params:[fromId:params.fromId])
            return
		
		}
     
		flash.message = "alterPage.not.deleted"
        flash.args = [params.id]
        redirect(controller:"alterPage", action:"show", id: params.id)
        return
    }

	
	/**
	 * Activa una pagina alternativa
	 * 
	 * retun
     *  redirect - /alterPage/show
     *  redirect - /alterPage/list
	 */
    def enable = {
		def instance = AlterPage.get(params.id)
		if ( !instance ) {
			flash.message = "alterPage.not.found"
			flash.args = [params.id]
			redirect(controller:"alterPage", action:"list")
			return
		}
		
		instance.disabled = false
		def result = comicService.changeProfile( instance )

		if(!result.hasErrors()){
			flash.message = "alterPage.updated"
			flash.args = [params.id]
            redirect(controller:"alterPage", action:"show", id:instance.id)
			return
		}
			
		redirect(controller:"alterPage", action:"show", id:instance.id)
		return
    }


	/**
	 * Desactiva una pagina alternativa
	 * 
	 * retun
     *  redirect - /alterPage/show
     *  redirect - /alterPage/list
	 */
    def disable = {
		def instance = AlterPage.get(params.id)
		if ( !instance ) {
			flash.message = "alterPage.not.found"
			flash.args = [params.id]
			redirect(controller:"alterPage", action:"list")
			return
		}
		
		instance.disabled = true
		def result = comicService.changeProfile( instance )

		if(!result.hasErrors()){
			flash.message = "alterPage.updated"
				flash.args = [params.id]
            redirect(controller:"alterPage", action:"show", id:instance.id)
			return
		}
			
		redirect(controller:"alterPage", action:"show", id:instance.id)
		return
    }

	
	/**
	 * Sol�licita moderacio per una pagina alternativa
	 * 
	 * retun
     *  redirect - /alterPage/show
     *  redirect - /alterPage/list
	 */	
	def moderationRequest = {
		def instance = AlterPage.get(params.id)
		
		if(!instance){
			flash.message = "flash.alterPage.not.found"
			flash.args = "${params.id}"
			redirect(controller:"alterPage", action:"list")
			return
		}

		instance.moderationRequest = true
		def result = pageService.changeProfile( instance )

		if(!result.hasErrors()){
			flash.message = "flash.alterPage.moderation.request"
			flash.args = [params.id]
            redirect(controller:"alterPage", action:"show", id:instance.id)
			return
		}
			
		redirect(controller:"alterPage", action:"show", id:instance.id)
		return
	}

	
	/**
	 * Valida que es correcte la pagina alternativa
	 * 
	 * retun
     *  redirect - /alterPage/show
     *  redirect - /alterPage/list
     *  redirect - /user/moderationRequests
	 */
	def moderate = {
		def instance = AlterPage.get(params.id)
		if ( !instance ) {
			flash.message = "flash.alterPage.not.found"
			flash.args = [params.id]
			redirect(controller:"alterPage", action:"list")
			return
		}
		
		instance.moderationRequest = false
		
		def result = pageService.changeProfile( instance )

		if(!result.hasErrors()){
			flash.message = "flash.alterPage.moderation.request"
			flash.args = [params.id]
            redirect(controller:"user", action:"moderationRequests")
			return
		}
			
		redirect(controller:"alterPage", action:"show", id:instance.id)
		return
    }
	
	
	/**
	 * Mostra els comentatis d'una pagina alternativa
	 * 
	 * retun
     *  render - /alterPage/list
	 */
	def comments = {
		params.max = Math.min(params.max ? params.max.toInteger() : 10,  100)
        
        def list = pageService.getAlterPageComments(params.max, params.offset?.toInteger(), params.sort, params.order, session['user']?.admin, params?.commentToId)
	    
        render(template:"/comment/list", model:[commentInstanceList: list['data'], commentInstanceTotal:list['count'], commentToName:'alterPage', commentToId:params.commentToId])
        return
    }
	
	
	/**
	 * Afegeix un comentati a una pagina alternativa
	 * 
	 * retun
     *  render - /alterPage/create
     *  redirect - /alterPage/comments
	 */
	def addComment = {
		def comment = new Comment(params)
		comment.createdBy = session['user']
		                            
		//	Si t� errors, mostrem la pantalla de creaci� d'un comentari.
        if (comment.hasErrors() ) {
    		render(template:"/comment/create", model:[commentInstance:comment, commentToName:params.commentToName, commentToId:params.commentToId])
    		return
        }
        
        def alterPage = AlterPage.get(params.commentToId.toLong())
		alterPage.addToComments(comment)
        
        flash.message = "flash.comment.saved"
        redirect(controller:"alterPage", action:"comments", params:[commentToId:params.commentToId])
        return
	}


	/**
	 * Afegeix un vot a un usuari
	 * Si es la primera vegada que un usuari vota a un usuari en concret, afegeix un vot
	 * si no, actualiza el vot
	 * 
	 * retun
	 *  render - /rate/rate
	 */
	def rate = {
		def alterPage = AlterPage.get(params.id)
		def userSession = User.get(session.user.ident())
		
		if(pageService.rateAlterPage(params.rating, alterPage, userSession)){
			//	Es puntua correctament
			render(template: "/rate/rate", model:[instance: alterPage, from:'alterPage', title:params.rating, yourRate:params.rating])
			return
		}else{
			//	Error al puntuar
			alterPage.errors.rejectValue("", "rate.fault")	
			render(template: "/rate/rateCustom", model:[instance: alterPage, from:'alterPage', title:params.rating])
			return
		}
	}
}
